<?php

namespace App\Http\Middleware\Home;

use App\Models\Category;
use App\Models\Communities;
use App\Models\District;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\View;

class Init
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        View::share('categories', Category::all()->sortBy('sort'));
        if (Auth::check()) {
            View::share('notifications_count', Auth::user()->unreadNotifications->count());
        }
//        $global_community_id = Cookie::get('community_id');
//        if ($global_community_id) {
//            View::share('global_community_id', $global_community_id);
//            $global_community          = Communities::find($global_community_id);
//            $request->global_community = $global_community;
//            View::share('global_community', $global_community);
//        }

        $domain = $_SERVER['HTTP_HOST'];
        $ex_domain = explode('.',$domain);
        if (count($ex_domain) > 2 && $ex_domain[0] != 'www') {
            $city = District::query()->where('domain_prefix',$ex_domain[0])->first();
            $request->global_city = $city;
            View::share('global_city', $city);
        }

        return $next($request);
    }
}
